package com.dreamwhale.machinery.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dreamwhale.machinery.config.DataResult;
import com.dreamwhale.machinery.dao.InfoCollectMapper;
import com.dreamwhale.machinery.dao.VipUserInfoMapper;
import com.dreamwhale.machinery.dao.YxStoreProductAttrValueMapper;
import com.dreamwhale.machinery.entity.InfoCollect;
import com.dreamwhale.machinery.entity.VipUserInfo;
import com.dreamwhale.machinery.entity.YxStoreProduct;
import com.dreamwhale.machinery.entity.YxStoreProductAttrValue;
import com.dreamwhale.machinery.goods.entity.ProductBrand;
import com.dreamwhale.machinery.goods.entity.YxStoreCart;
import com.dreamwhale.machinery.goods.entity.YxStoreOrder;
import com.dreamwhale.machinery.goods.mapper.ProductBrandMapper;
import com.dreamwhale.machinery.goods.mapper.YxStoreCartMapper;
import com.dreamwhale.machinery.goods.mapper.YxStoreOrderMapper;
import com.dreamwhale.machinery.goods.mapper.YxStoreProductMapper;
import com.dreamwhale.machinery.user.entity.UserShop;
import com.dreamwhale.machinery.user.entity.YxUser;
import com.dreamwhale.machinery.user.mapper.UserShopMapper;
import com.dreamwhale.machinery.user.mapper.YxUserMapper;
import com.dreamwhale.machinery.user.service.YxUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dreamwhale.machinery.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.relational.core.sql.In;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Author
 * @since 2020-05-27
 */
@Service
public class YxUserServiceImpl extends ServiceImpl<YxUserMapper, YxUser> implements YxUserService {
    @Resource
    private YxUserMapper yxUserMapper;

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private RedisUtils<String> strRedisUtils;

    @Resource
    private AliSmsUtils aliSmsUtils;


    @Resource
    private YxStoreCartMapper yxStoreCartMapper;

    @Resource
    private InfoCollectMapper infoCollectMapper;

    @Resource
    private YxStoreOrderMapper yxStoreOrderMapper;

    @Resource
    private YxStoreProductMapper yxStoreProductMapper;

    @Resource
    private UserShopMapper userShopMapper;

    @Resource
    private ProductBrandMapper productBrandMapper;
    @Resource
    private YxStoreProductAttrValueMapper yxStoreProductAttrValueMapper;

    @Resource
    private VipUserInfoMapper vipUserInfoMapper;

    @Override
    public DataResult userRegister(YxUser yxUser, String code) {
        if (StringUtils.isBlank(yxUser.getPhone())) {
            return new DataResult(300, "登录信息不完整", null);
        }
        String read = strRedisUtils.read(String.format("Sms-%s", yxUser.getPhone()));
        if (!read.equals(code)) {
            return new DataResult(300, "验证码不正确", null);
        }
        Integer phoneCount = yxUserMapper.selectCount(new QueryWrapper<YxUser>().eq("account", yxUser.getPhone()).or().eq("phone", yxUser.getPhone()));
        Integer accountCount = yxUserMapper.selectCount(new QueryWrapper<YxUser>().eq("account", yxUser.getAccount()).or().eq("phone", yxUser.getAccount()));
        if (phoneCount != 0 || accountCount != 0) {
            return new DataResult(300, "账号已被注册", null);
        }
        yxUser.setAccount(yxUser.getPhone());
        yxUser.setPassword(DigestUtils.md5DigestAsHex(yxUser.getPwd().getBytes()));
        int insert = yxUserMapper.insert(yxUser);
        if (insert == 1) {
            return new DataResult(200, "注册成功", null);
        }
        return new DataResult(300, "注册失败", null);
    }

    @Override
    public DataResult userLogin(String account, String password, String code) {
        if (StringUtils.isBlank(account) || (StringUtils.isBlank(password) && StringUtils.isBlank(code))) {
            return new DataResult(300, "登录信息不完整", null);
        }
        YxUser yxUser;
        try {
            yxUser = yxUserMapper.selectOne(new QueryWrapper<YxUser>().eq("account", account).or().eq("phone", account));
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResult(300, "登陆失败联系客服", null);
        }
        if (yxUser == null) {
            return new DataResult(300, "账号或密码错误", null);
        }
        if (StringUtils.isNotBlank(password)) {
            String s = DigestUtils.md5DigestAsHex(password.getBytes());
            if (!s.equals(yxUser.getPassword())) {
                return new DataResult(300, "账号或密码错误", null);
            }
        } else {
            String read = strRedisUtils.read(String.format("Sms-%s", yxUser.getPhone()));
            if (read.equals(code)) {
                return new DataResult(300, "验证码不正确", null);
            }

        }
        String jwtToken = jwtUtils.createJwtToken(8640000L, yxUser.getUid().longValue());
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("uid", yxUser.getUid().longValue());
        resultMap.put("account", yxUser.getAccount());
        resultMap.put("realName", yxUser.getRealName());
        resultMap.put("birthday", yxUser.getBirthday());
        resultMap.put("nickname", yxUser.getNickname());
        resultMap.put("avatar", yxUser.getAvatar());
        resultMap.put("phone", yxUser.getPhone());
        resultMap.put("nowMoney", yxUser.getNowMoney());
        resultMap.put("signNum", yxUser.getSignNum());
        resultMap.put("level", yxUser.getLevel());
        resultMap.put("userType", yxUser.getUserType());
        resultMap.put("url","http://login.jxzd.top/speedPage.html?userId="+ yxUser.getUid());
        resultMap.put("token", jwtToken);

        List<VipUserInfo> vipUserInfos = vipUserInfoMapper.selectList(new QueryWrapper<VipUserInfo>().eq("uid", yxUser.getUid().longValue()).orderByDesc("expiration_time"));
        resultMap.put("vipStatus", false);
        if (!CollectionUtils.isEmpty(vipUserInfos)) {
            VipUserInfo vipUserInfo = vipUserInfos.get(0);
            LocalDateTime expirationTime = vipUserInfo.getExpirationTime();
            resultMap.put("vipStatus", expirationTime.compareTo(LocalDateTime.now()) > 0);
            resultMap.put("vipValidTime", expirationTime);
        }
        return new DataResult(200, "登录成功", resultMap);
    }

    @Override
    public DataResult GetVerificationCode(String phone) {
        String verification = WorkIdUtils.generateRandomCode(6);
        strRedisUtils.write(String.format("Sms-%s", phone), verification);
        AliSmsUtils.Sms sms = new AliSmsUtils.Sms();
        sms.setCode(verification);
        System.out.println(sms);
        if (aliSmsUtils.toSend(phone, "SMS_168890123", JSON.toJSONString(sms))) {
            return new DataResult(200, "发送成功", null);
        }
        return new DataResult(300, "发送失败", null);
    }

    @Override
    public DataResult GetPersonalInformation(Integer userId) {

        Integer cartCount = yxStoreCartMapper.selectCount(new QueryWrapper<YxStoreCart>().eq("uid", userId));

//        Integer cartCount = yxStoreCartMapper.selectCount(new QueryWrapper<YxStoreCart>().eq("uid", userId));
//
//        Integer cartCount = yxStoreCartMapper.selectCount(new QueryWrapper<YxStoreCart>().eq("uid", userId));
//
//        Integer cartCount = yxStoreCartMapper.selectCount(new QueryWrapper<YxStoreCart>().eq("uid", userId));


        return null;
    }

    @Override
    public int updateMyPassWords(YxUser yxUser) {
        return yxUserMapper.updateById(yxUser);
    }

    @Override
    public List<YxStoreOrder> inquiryOrder(Integer userId, Integer type) {
        QueryWrapper<YxStoreOrder> yxStoreOrderQueryWrapper = new QueryWrapper<YxStoreOrder>().eq("uid", userId);
        if (type != null) {
            if (type != -1)
                yxStoreOrderQueryWrapper.eq("status", type);
            else
                yxStoreOrderQueryWrapper.in("status", -1, -2, -3);

        }
        yxStoreOrderQueryWrapper.eq("is_del", 0);
        List<YxStoreOrder> yxStoreOrders = yxStoreOrderMapper.selectList(yxStoreOrderQueryWrapper);
        for (YxStoreOrder yxStoreOrder : yxStoreOrders) {
            //购物车
            QueryWrapper<YxStoreCart> yxStoreCartQueryWrapper = new QueryWrapper<>();
            yxStoreCartQueryWrapper.eq("id", yxStoreOrder.getCartId());
            List<YxStoreCart> listc = yxStoreCartMapper.selectList(yxStoreCartQueryWrapper);
            yxStoreOrder.setProductAttrUnique(listc.get(0).getProductAttrUnique());//规格
            yxStoreOrder.setCartNum(listc.get(0).getCartNum());//数量
            //商品
            QueryWrapper<YxStoreProduct> yxStoreProductQueryWrapper = new QueryWrapper<>();
            yxStoreCartQueryWrapper.eq("id", listc.get(0).getProductId());
            List<YxStoreProduct> listp = yxStoreProductMapper.selectList(yxStoreProductQueryWrapper);
            yxStoreOrder.setStoreName(listp.get(0).getStoreName());//商品名称
            yxStoreOrder.setProductImage(listp.get(0).getImage());//商品图片

            YxStoreProductAttrValue yxStoreProductAttrValue = yxStoreProductAttrValueMapper.selectOne(new QueryWrapper<YxStoreProductAttrValue>().eq("product_id", listc.get(0).getProductId()).eq("suk", listc.get(0).getProductAttrUnique()));

            yxStoreOrder.setPrice(yxStoreProductAttrValue == null ? listc.get(0).getPrice() : yxStoreProductAttrValue.getPrice());//商品单价
            //商户
            QueryWrapper<UserShop> userShopQueryWrapper = new QueryWrapper<>();
            yxStoreCartQueryWrapper.eq("id", listp.get(0).getMerId());
            List<UserShop> listu = userShopMapper.selectList(userShopQueryWrapper);
            yxStoreOrder.setMerchantName(listu.get(0).getMerchantName());//商户名称

        }
        return yxStoreOrders;
    }

    @Override
    public DataResult inquiryOrderInfo(String orderId) {
        YxStoreOrder storeOrder = yxStoreOrderMapper.selectOne(new QueryWrapper<YxStoreOrder>().eq("order_id", orderId));
        Map<String, Object> objectHashMap = new HashMap<>();
        ArrayList<Map<String, Object>> resultMapList = new ArrayList<>();
        if (storeOrder != null) {
            String[] split = storeOrder.getCartId().split(",");
            List<Integer> collect = Arrays.stream(split).mapToInt(Integer::parseInt).boxed().collect(Collectors.toList());
            List<YxStoreCart> yxStoreCart = yxStoreCartMapper.selectList(new QueryWrapper<YxStoreCart>().in("id", collect));
            for (YxStoreCart storeCart : yxStoreCart) {
                Integer productId = storeCart.getProductId();
                YxStoreProduct yxStoreProduct = yxStoreProductMapper.selectById(productId);
                Map<String, Object> map = new HashMap<>();
                //map.putAll(MapUtils.entityToMap(yxStoreProduct));
                map.put("storeCart", storeCart);
                Integer brandId = yxStoreProduct.getBrandId();

                UserShop userShop = userShopMapper.selectById(yxStoreProduct.getMerId());
                ProductBrand productBrand = productBrandMapper.selectById(brandId);
                Map<String, Object> map1 = MapUtils.entityToMap(yxStoreProduct);
                map1.put("bandName", productBrand.getName());
                map1.put("merchantName", userShop.getMerchantName());
                map.put("storeProduct", map1);
                resultMapList.add(map);
            }
            objectHashMap.put("productInfo", resultMapList);
            objectHashMap.put("orderInfo", storeOrder);
        }
        return new DataResult(200, "查询成功", objectHashMap);
    }

    @Override
    public DataResult inquiryConsultingCollection(Integer userId, Integer type) {
        List<InfoCollect> infoCollectList = infoCollectMapper.selectList(new QueryWrapper<InfoCollect>().eq("userId", userId));
        return new DataResult(200, "查询成功", infoCollectList);
    }

    public Map selectYxUserByUserId(Integer userId) {
        YxUser yxUser = yxUserMapper.selectById(userId);
        Map<String, Object> map = MapUtils.entityToMap(yxUser);
        List<VipUserInfo> vipUserInfos = vipUserInfoMapper.selectList(new QueryWrapper<VipUserInfo>().eq("uid", userId).orderByDesc("expiration_time"));
        map.put("vipStatus", false);
        if (!CollectionUtils.isEmpty(vipUserInfos)) {
            VipUserInfo vipUserInfo = vipUserInfos.get(0);
            LocalDateTime expirationTime = vipUserInfo.getExpirationTime();
            map.put("vipStatus", expirationTime.compareTo(LocalDateTime.now()) > 0);
            map.put("vipValidTime", expirationTime);
        }
        return map;
    }

    @Override
    public DataResult inquiryMyOrder(Integer userId, Integer type) {
        return null;
    }

    @Override
    public DataResult changeUserInfo(YxUser yxUser, Integer userId) {
        return null;
    }
}
